﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Reflection;

namespace BlueFlyPhone
{

    public static class StringExtensions
    {


        public static string NonNullTrimmed(string val)
        {
            if (!string.IsNullOrEmpty(val))
            {

                return val.Trim();

            }

            return null;
        
        }


        public static string PropertyKey<T>(this T item,   Expression<Func<T,object>> expression)
        {
            MemberExpression propertyExpression = (MemberExpression)expression.Body;
            MemberInfo propertyMember = propertyExpression.Member;

            KeyAttribute[] displayAttributes = (KeyAttribute[])propertyMember.GetCustomAttributes(typeof(KeyAttribute), true);
            if (displayAttributes != null && displayAttributes.Length == 1)
                return ((KeyAttribute)displayAttributes[0]).Name;

            return propertyMember.Name;
        }
         

        public static void WriteRecord<T>(this System.IO.StreamWriter sw, T obj ,Expression<Func<T, object>> expression)
        {

            MemberExpression ex =(MemberExpression) expression.Body;

            ParameterExpression p = Expression.Parameter(typeof(T), "x");

            MemberInfo mi =  typeof(T).GetRuntimeProperty(ex.Member.Name);
       
            MemberExpression m = Expression.MakeMemberAccess(p, mi );

            var result = Expression.Lambda<Func<T, object>>(m, p).Compile()(obj);


            KeyAttribute[] displayAttributes = (KeyAttribute[])mi.GetCustomAttributes(typeof(KeyAttribute), true);
            if (displayAttributes != null && displayAttributes.Length == 1)
            {
                string key = ((KeyAttribute)displayAttributes[0]).Name;
                bool required = ((KeyAttribute)displayAttributes[0]).Required;

                if (result!=null)
                {
                    sw.Write(key);
                    sw.WriteLine(result);
                }
                else if (required)
                {
                    //throw new Exception("required");
                }



            }

        }

    }
}
